package cn.itcast.bos.web.action.take_delivery;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.take_delivery.WayBillService;
import cn.itcast.bos.web.action.common.BaseAction;

@Controller
@Scope("prototype")
@Namespace("/")
@ParentPackage("json-default")
public class WayBillAction extends BaseAction<WayBill> {
	//日志
	private static final Logger LOGGER	= Logger.getLogger(WayBillAction.class);
	
	@Autowired
	private WayBillService wayBillService;
	
	//保存运单
	@Action(value="waybill_save",results={@Result(name="success",type="json")})
	public String save(){
		//去除没有id的order对象
		if(model.getOrder()!=null && (model.getOrder().getId()==null || 
				model.getOrder().getId()==0)){
			model.setOrder(null);
		}
		
		//调用service层,保存运单		
		wayBillService.save(model);
		//新建一个map集合,用于存储返回到客户端页面结果 
		Map<String,Object> map = new HashMap<>();
		map.put("result",true);
		map.put("msg", "运单保存成功");
		LOGGER.info("保存运单成功:"+model.getWayBillNum());
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	
	//分页查询运单
	@Action(value="waybill_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		//创建pageable对象
		Pageable pageable = new PageRequest(page-1, rows,new Sort(new Sort.Order(Sort.Direction.DESC, "id")));
		//调用service层,处理数据
		Page<WayBill> pageData = wayBillService.pageQuery(model,pageable);
		//处理接受到的数据,压入栈顶
		pushPageDataToValueStack(pageData);
		return SUCCESS;
	}
	
	//根据运单id回显数据
	@Action(value="waybill_waybillData",results={@Result(name="success",type="json")})
	public String findWayBillDataByWayBillNum(){
		//创建一个map对象,用于封装数据
		Map<String,Object> map = new HashMap<>();
		//调用service层处理数据,传入id
		WayBill wayBill = wayBillService.findWayBillDataByWayBillNum(model.getWayBillNum());
		System.out.println("运单:"+wayBill);
		//接受返回的waybill对象,判断是否为空
		if(null!=wayBill){
			//若不为空,保存数据
			map.put("success", true);
			map.put("wayBillData", wayBill);
		}else{
			map.put("success", false);
		}
			//将数据结果压入栈顶
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	
	
	
}
